package com.xiaomo.gitee.datamanager.util;


import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "jwt")
@NoArgsConstructor
public class JwtUtils {

    private int expire;
    private String key;

    private static final String ALG = "HS256";
    private static JWTSigner jwtSigner;
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    @PostConstruct
    public void init() {
        jwtSigner = JWTSignerUtil.hs256(key.getBytes());
    }

    public String generateJwt(String userId) {
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + expire* 1000L);
        return JWT.create()
                .setHeader("typ","JWT")
                .setHeader("alg",ALG)
                .setPayload("userId",userId)
                .setExpiresAt(expireTime)
                .setIssuedAt(now)
                .setSigner(jwtSigner)
                .sign();

    }

    public boolean isValidToken(String jwt) {
//        return JWT.of(jwt).setSigner(jwtSigner).validate(0);
        boolean result = false;
        try {
            result = JWTUtil.verify(jwt,key.getBytes());
            JWTValidator.of(jwt).validateDate(new Date());
        } catch (Exception e) {
            return false;
        }
        return result;
    }

    public JSONObject getPayloadArguments(String jwt) {
        return JWT.of(jwt).getPayloads();
    }

    public Cookie getJwtCookie(String userId) {
        String jwt = generateJwt(userId);
        Cookie cookie = new Cookie(TOKEN_HEADER,jwt);
        cookie.setMaxAge(expire);
        return cookie;
    }

    public static String getJwtTokenFromHttpHeader(HttpServletRequest request) {
        String header = request.getHeader(TOKEN_HEADER);
        if (header == null || !header.startsWith(TOKEN_PREFIX)) {
            return null;
        }
        return header.split(" ")[1].trim();
    }

    public JSONObject getHeaderArguments(String jwt) {
        return JWT.of(jwt).getHeaders();
    }
}
